

public class MyLooper {

    static  final ThreadLocal<MyLooper> mthreadlocal = new ThreadLocal<MyLooper>();

    MyMessageQueue mqueue;

    private MyLooper() {
        mqueue = new MyMessageQueue();
    }

    public static MyLooper myLooper() {
        return mthreadlocal.get();
    }

    public static void prepare() {
        if (mthreadlocal.get() != null) {
            throw new RuntimeException("only one looper may be created per thread");
        }
        mthreadlocal.set(new MyLooper());
    }

    public static void loop(){
        MyLooper looper = myLooper();
        if (looper==null){
            throw new RuntimeException("No looper");
        }

        MyMessageQueue queue=looper.mqueue;
        for (;;){
            MyMessage msg=queue.next();
            if (msg==null&&msg.target==null){
                continue;
            }
            msg.target.dispatchMessage(msg);

        }
    }
}
